package cool.taomu.toolkit.thymeleaf

import com.google.common.io.Resources
import java.io.File
import java.io.StringWriter
import java.net.URL
import java.nio.charset.Charset
import java.util.Map
import org.apache.commons.io.FileUtils
import org.apache.commons.lang3.exception.ExceptionUtils
import org.slf4j.LoggerFactory
import org.thymeleaf.TemplateEngine
import org.thymeleaf.context.Context
import cool.taomu.toolkit.template.ITemplate

class ThymeleafUtils implements ITemplate{
	val static LOG = LoggerFactory.getLogger(ThymeleafUtils);

	def thymeleaf(URL url, Map<String, Object> dataModel) {
		var writer = new StringWriter();
		try {
			LOG.info("thymeleaf 模板路径：{}", url.path);
			var content = Resources.toString(url, Charset.forName("UTF-8"))
			var templateEngine = new TemplateEngine();
			val context = new Context();
			dataModel.forEach [ k, v |
				context.setVariable(k, v);
			]
			templateEngine.process(content, context, writer)
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer;
	}

	override execute(String path, Map<String, Object> dataModel) {
		var writer = new StringWriter();
		try {
			var content = FileUtils.readFileToString(new File(path), "UTF-8");
			var templateEngine = new TemplateEngine();
			val context = new Context();
			dataModel.forEach [ k, v |
				context.setVariable(k, v);
			]
			templateEngine.process(content, context, writer)
		} catch (Exception ex) {
			writer.flush();
			LOG.info(ExceptionUtils.getStackTrace(ex));
			writer.append(ExceptionUtils.getStackTrace(ex))
		}
		return writer;
	}
}
